package com.example.demo.demos.config;

import com.example.demo.demos.websocket.AuthWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author lyh
 * @date 2025/7/21 16:55
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(authWebSocketHandler(), "/ws")
                .setAllowedOrigins("*"); // 允许跨域
    }

    @Bean
    public AuthWebSocketHandler authWebSocketHandler() {
        return new AuthWebSocketHandler();
    }

    // 添加服务器绑定地址配置
//    @Bean
//    public String serverAddress() throws UnknownHostException {
//        // 绑定到0.0.0.0而不是localhost
//        System.setProperty("server.address", "0.0.0.0");
//        // 打印实际绑定IP（调试用）
//        InetAddress ip = InetAddress.getLocalHost();
//        System.out.println("WebSocket服务绑定地址: " + ip.getHostAddress());
//        return ip.getHostAddress();
//    }
}
